#!/usr/bin/env python
# -*- coding: UTF-8 -*-

try:
	import pygame
	import sys
	from pygame.locals import *
	import lib.utils
except ImportError, err:
	print "Could not load %s module." % (err)
	sys.exit(2)

class InfoBar(pygame.sprite.DirtySprite):
	"""
	Object for the Info Bar at the bottom
	"""
	def __init__(self, field, layers):
		pygame.sprite.DirtySprite.__init__(self)

		#loads, scales and transparencies the info bar image
		self.image = pygame.transform.scale(lib.utils.load_image('./data/rescs/DOWNBAR.pcx'), (800, 100))
		self.image.set_colorkey((255, 67, 255))
		#init some variables
		self.rect = Rect(0, 500, 800, 100)

		self.field_moved = False

		self.battlefield = field
		self.layers = layers

		self.info = {}
		self.info['terrain_img'] = InfoBarTerrainImg()
		self.info['terrain_bonus'] = InfoBarTerrainBonus()
		self.info['movement_cost'] = InfoBarMovement()
		self.info['unit_MV'] = InfoBarUnitMV()
		self.info['phase_counter'] = InfoBarPhaseCounter()

		[self.layers.add(x, layer = 4) for x in self.info.values()]



		self.data = {}

		self.x = 0
		self.y = 0

		#needs something fixed width for consistency
		self.font = lib.utils.get_window_font()

		self.info['phase_counter'].set(1, self.font)

	def update(self):
		"""
		Updates the Info Bar

		Also updates the cursor! Tests if cursor position changed, then updates
		unit highlighting and NA emblem

		Currently hacked so info bar doesn't update info until cursor/battlefield
		stops moving
		"""
		x, y = self.cursor.get_tile_pos()

		if self.battlefield.is_animating():
			self.field_moved = False

		if (self.x != x or self.y != y) and self.field_moved \
				and not self.cursor.is_animating():
			self.units.focus_unit(x, y)
			self.update_sprites()





	def update_sprites(self):
		"""
		Updates the sprites under the Info Bar
		"""

		x, y = self.cursor.get_tile_pos()
		self.field_moved = False
		#gets data from relevant tile to be displayed
		self.data['terrain_img'], self.data['terrain_bonus'], self.data['movement_cost'] = self.battlefield[x][y].get_data()[2:5]

		#sets new x and y values
		self.x = x
		self.y = y

		if self.info['terrain_img'].data != self.data['terrain_img']:
			self.info['terrain_img'].set(self.data['terrain_img'])

		if self.info['movement_cost'].data != self.data['movement_cost']:
			self.info['movement_cost'].set(str(self.data['movement_cost']), self.font)

		bonus = "%+3d%%" % (self.data['terrain_bonus'],)
		if self.info['terrain_bonus'].data != bonus:
			self.info['terrain_bonus'].set(bonus, self.font)

		if self.units[x][y]:

			if self.info['unit_MV'].data != self.units[x][y].MV:
				self.info['unit_MV'].set(str(self.units[x][y].MV), self.font)
		else:
			self.info['unit_MV'].clear()

	def set_cursor(self, cursor):
		"""
		Sets the cursor + units so its position can be found.
		Not used?
		"""
		self.cursor = cursor
		self.units = self.layers.get_sprites_from_layer(2)[0]

		x, y = self.cursor.get_tile_pos()
		if self.units[x][y]:
			self.units.focus_unit(x, y)
		self.update_sprites()

	def update_phase(self, phase):
		"""
		Updates infobar with new phase
		"""
		self.info['phase_counter'].set(phase, self.font)


	def move(self, key, mod):
		"""
		Passes movement calls from the engine as the Info Bar doesn't move
		"""
		pass

	def r_move(self, key, mod):
		"""
		Passes movement calls from the engine as the Info Bar doesn't move
		"""
		pass


"""
Sprites used in the Info Bar

Some have specialized methods to load their required objects
"""

class InfoBarTerrainImg(pygame.sprite.DirtySprite):
	"""
	Terrain Mini-Image
	"""
	def __init__(self):
		pygame.sprite.DirtySprite.__init__(self)
		self.image = pygame.Surface((60, 40))
		self.rect = Rect(20, 540, 60, 40)
		self.terrain_imgs = []
		#placeholder for later options on terrain mini-images
		self.load_terrain_images('./data/maps/terrain.pcx')
		self.data = None

	def load_terrain_images(self, file):
		"""
		Loads the terrain mini-images into the object
		"""
		img = lib.utils.load_image(file)
		w, h = img.get_size()
		w = w / 48
		h = h / 32

		#Subsurface + scales all of the mini-images at 48x32 to 60x40 size
		for y in xrange(h):
			for x in xrange(w):
				self.terrain_imgs.append(pygame.transform.scale(img.subsurface((x * 48, y * 32, 48, 32)), (60, 40)))

	def set(self, data):
		self.data = data
		self.image.blit(self.terrain_imgs[data], (0,0))
		self.dirty = 1





class InfoBarTerrainBonus(pygame.sprite.DirtySprite):
	"""
	Terrain Bonus +-##%
	"""
	def __init__(self):
			pygame.sprite.DirtySprite.__init__(self)
			self.image = pygame.Surface((60, 40), SRCALPHA, 32).convert_alpha()
			self.rect = Rect(80, 542, 60, 40)
			self.data = None

	def set(self, data, font):
		self.data = data
		self.image.fill((0, 0, 0, 0))
		self.image.blit(font.render(data , True, (255, 255, 255)), (0, 0))
		self.dirty = 1

class InfoBarUnitMV(pygame.sprite.DirtySprite):
	"""
	Unit Movement - Debug
	"""
	def __init__(self):
			pygame.sprite.DirtySprite.__init__(self)
			self.image = pygame.Surface((60, 40), SRCALPHA, 32).convert_alpha()
			self.rect = Rect(150, 542, 60, 40)
			self.data = None

	def set(self, data, font):
		self.data = data
		self.image.fill((0, 0, 0, 0))
		self.image.blit(font.render(data , True, (255, 255, 255)), (0, 0))
		self.dirty = 1

	def clear(self):
		if self.data:
			self.data = None
			self.image.fill((0, 0, 0, 0))
			self.dirty = 1

class InfoBarMovement(pygame.sprite.DirtySprite):
	"""
	Terrain Movement - Debug
	"""
	def __init__(self):
			pygame.sprite.DirtySprite.__init__(self)
			self.image = pygame.Surface((60, 40), SRCALPHA, 32).convert_alpha()
			self.rect = Rect(250, 542, 60, 40)
			self.data = None

	def set(self, data, font):
		self.data = data
		self.image.fill((0, 0, 0, 0))
		self.image.blit(font.render(data , True, (255, 255, 255)), (0, 0))
		self.dirty = 1

	def clear(self):
		if self.data:
			self.data = None
			self.image.fill((0, 0, 0, 0))
			self.dirty = 1


class InfoBarPhaseCounter(pygame.sprite.DirtySprite):
	"""
	Terrain Movement - Debug
	"""
	def __init__(self):
			pygame.sprite.DirtySprite.__init__(self)
			self.image = pygame.Surface((60, 40), SRCALPHA, 32).convert_alpha()
			self.rect = Rect(500, 542, 60, 40)
			self.data = 0

	def set(self, data, font):
		self.data = data
		self.image.fill((0, 0, 0, 0))
		self.image.blit(font.render(str(data) , True, (255, 255, 255)), (0, 0))
		self.dirty = 1
